<?php
namespace app\common\library\xilujob\resume;


use app\common\model\xilujob\Resume;
use think\Exception;
use think\Model;
use think\Validate;

abstract class BaseModule {

    protected $name;
    protected $resume;

    public function __construct(Resume $resume) {
        $this->resume = $resume;
    }

    public abstract function onCreateResume(Resume $resume);

    /**
     * Override this method to support adding record
     * @param $data
     * @throws ModuleException
     * @return Model|string
     */
    public function add($data) {
        $data = array_intersect_key($data, array_flip((array) $this->keys()));
        $rules = $this->getRules();
        $validator = new Validate($rules);
        if(!$validator->check($data)) {
            throw new ModuleException($validator->getError());
        }
        $record = $this->getModel();
        $data['user_id'] = $this->resume->user_id;
        $data['resume_id'] = $this->resume->id;
        if($record->save($data)===false) {
            throw new ModuleException($record->getError());
        }
        return $record;
    }

    /**
     * @param array $data 必须有id
     * @return Model|string
     */
    public function edit($data) {
        if(!isset($data['id']) || !is_numeric($data['id'])) {
            throw new ModuleException('Invalid Arguments');
        }
        $id = $data['id'];
        $data = array_intersect_key($data, array_flip((array) $this->keys()));
        $rules = $this->getRules();
        $validator = new Validate($rules);
        if(!$validator->check($data)) {
            throw new ModuleException($validator->getError());
        }
        $record = $this->getModel()->get($id);
        if(!$record) {
            throw new ModuleException('记录没有找到');
        }
        if($record->resume_id!=$this->resume->id) {
            throw new ModuleException('Invalid Arguments');
        }
        if($record->save($data)===false) {
            throw new ModuleException($record->getError());
        }
        return $record;
    }

    /**
     * @param $id
     * @return string|Model
     */
    public function del($id) {
        if(!$id || !is_numeric($id)) {
            throw new ModuleException('Invalid Arguments');
        }
        $record = $this->getModel()->get($id);
        if(!$record) {
            throw new ModuleException('记录没有找到');
        }
        if($record->resume_id!=$this->resume->id) {
            throw new ModuleException('Invalid Arguments');
        }
        $record->delete();
        return $record;
    }

    /**
     * 获取所有字段的key
     * @return array
     */
    protected abstract function keys();

    /**
     * 获取验证规则
     * @return array
     */
    protected abstract function getRules();

    /**
     * 获得Model实例
     * @return Model
     */
    protected abstract function getModel();

    /**
     * @return array score: 当前分数， max: 满分
     */
    protected abstract function getCompleteScore();

}